package com.le.tester.webpage.lock;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：ReentrantLock的有序性
 */
public class ReentrantLockPractice {
    public int count;
    private static final Logger LOG = LoggerFactory.getLogger(ReentrantLockPractice.class);
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static String[] threadNameArr = {"A", "B", "C"};

    public static void main(String[] args) {
        ReentrantLockPractice reentrantLockPractice = new ReentrantLockPractice();
        reentrantLockPractice.startDemo();
    }

    private void startDemo() {
        for (int i = 0; i < 10; i++) {
            //10次的线程名，3个线程名
            for (String name : threadNameArr) {
                TestThread testThread = new TestThread(name, this);
                testThread.start();
                //try {
                //这里有顺序输出的是这个线程的休眠的动作，100ms足以让线程有足够的时间排队了，
                //去除掉锁的情况下，依旧是有顺序的输出
                //Thread.sleep(100);
                //} catch (InterruptedException e) {
                //throw new RuntimeException(e.getMessage());
                //}
            }
        }
    }

    static class TestThread extends Thread {
        ReentrantLockPractice reentrantLockPractice;

        TestThread(String name, ReentrantLockPractice reentrantLockPractice) {
            super(name);
            this.reentrantLockPractice = reentrantLockPractice;
        }

        @Override
        public void run() {
            try {
                //锁住了count++;没锁住Thread.currentThread().getName();
                reentrantLock.lock();
                System.out.println("count:" + reentrantLockPractice.count++);
                System.out.println(Thread.currentThread().getName());
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                reentrantLock.unlock();
            }
        }
    }
}
